<!-- 这药品信息管理页面 -->

<template>
  <div class="medicationInfo">
    <el-card shadow="never">
      <!-- 顶部按钮栏 -->
      <div class="topBar" style="width:100%;text-align: right">
        <el-button type="primary" plain :icon="CirclePlus" @click="scanInput">扫码录入</el-button>
        <el-button type="primary" plain :icon="Upload" @click="add">新增药品</el-button>
        <el-button type="primary" plain :icon="Download" @click="download">导出表格</el-button>
        <!-- 分割线 -->
        <el-divider ></el-divider>
      </div>
      <!-- 搜索框栏 -->
      <div class="searchBar" style="width:100%;display: flex;flex-direction: row; align-items: center;">
        <!-- 药品名称输入框 -->
        <el-form-item>
          <el-input placeholder="请输入药品名称" v-model="formData.name" @keyup.enter="debounceSearch">
            <template #append>
              <el-button style="color: #FFFFFF;background-color: #3b82f6;" :icon="Search" @click="debounceSearch" />
            </template>
          </el-input>
        </el-form-item>
      </div>
      <!--药品表格-->
      <el-card v-loading="loading" style="width: 100%;margin-top: 20px;color: #333333;"  shadow="never">
        <el-table :data="medicineData" style="width: 100%;font-size: 14px;" stripe   show-overflow-tooltip :default-sort="{ prop: 'price', order: 'descending' }" >
          <el-table-column fixed type="index" width="60" label="序号" align="center"></el-table-column>
          <el-table-column fixed prop="name" label="药品名称" width="155" align="center"></el-table-column>
          <el-table-column prop="specification" label="药品规格" width="120" align="center"></el-table-column>
          <el-table-column prop="dosage" label="药品剂型" width="80" align="center"></el-table-column>
          <el-table-column prop="category" label="药品类别" width="120" align="center"></el-table-column>
          <el-table-column prop="approvalNum" label="药品批准文号" width="160" align="center"></el-table-column>
          <el-table-column prop="insuranceCode" label="医保编码" width="120" align="center"></el-table-column>
          <el-table-column prop="indication" label="功能主治" align="center"></el-table-column>
          <el-table-column prop="price" label="售药价" width="100" align="center" sortable></el-table-column>
          <el-table-column prop="manufacturer" label="生产厂家" width="120" align="center"></el-table-column>
          <el-table-column prop="storageLocation" label="存放货架" align="center"></el-table-column>
          <el-table-column prop="amount" label="库存数量" align="center"></el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="160" align="center" sortable></el-table-column>
          <el-table-column fixed="right" label="操作" width="240" align="center">
            <template #default="scope">
              <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑基本信息</el-button>
              <el-button type="success" plain size="small" @click="stockManage(scope.$index, scope.row)">库存管理</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin:30px;float: right;">
          <el-pagination
              size="small"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[5, 10, 15, 20]"
              v-model:current-page="currentPage"
              v-model:page-size="currentSize"
              v-model:total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </el-card>
    <!-- 扫码录入弹框-->
    <el-dialog title="扫码录入" v-model="dialogVisible" width="30%" :before-close="handleClose">
      <div style="text-align: center;">
        <el-image :src="addCodeImage" style="width: 200px;height: 200px;"></el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
/*引入所需的icon图标*/
import { CirclePlus ,Upload , Download, Search } from "@element-plus/icons"
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import {debounce} from "lodash";
import ExcelJS from "exceljs"; // 引入 exceljs 库
import saveAs from "file-saver"; // 引入 file-saver 库
/*引入图片资源*/
import addCodeImage from "../../assets/images/addCode.png";
/*定义控制扫码录入弹框的变量*/
const dialogVisible = ref(false);
/*定义扫码录入方法*/
const scanInput = () => {
  dialogVisible.value = true;
};
/*定义扫码录入弹框关闭方法*/
const handleClose = (done) => {
  dialogVisible.value = false;
};
/*定义新增方法*/
const add = () => {
  ElMessage({
    message: "新增功能开发中...",
    type: "success"
  });
};
/*定义导出方法*/
const download = () => {
  console.log("点击了导出方法");
  axios.get(TEST_URL+"/v1/medicine/export").then((res) => {
    loading.value = true;
    console.log("导出接口响应数据：{}",res.data);
    if(res.data.code == 2001){
      // 将数据转换为 Excel 文件并下载
      exportToExcel(res.data.data);
      ElMessage({
        message: "导出成功",
        type: "success"
      });
      loading.value = false;
    }else {
      ElMessage({
        message: "导出失败，请稍后再试",
        type: "error"
      });
    }
  });
};
/*定义加载动画*/
const loading = ref(false);
/*定义表单数据*/
const formData = ref({
  name: "",
});
/*定义搜索表单*/
const search = () => {
  console.log("执行搜索药品方法")
  loading.value = true;
  formData.value.pageSize = currentSize.value;
  formData.value.pageNum = currentPage.value;
  let data = qs.stringify(formData.value);
  console.log("请求参数：药品名称+每页显示多少条+显示页码{}",data);
  axios.post(TEST_URL+"/v1/medicine/select?"+data).then((res) => {
    console.log("药品查询接口响应数据：{}",res.data);
    if(res.data.code == 2001){
      medicineData.value = res.data.data.list;
      total.value = res.data.data.total;//设置总条目数
      loading.value = false;
    }else {
      ElMessage({
        message: "查询失败，请稍后再试",
        type: "error"
      });
      loading.value = false;
    }
  });
};
/*定义药品数据*/
const medicineData = ref([]);
/*页面加载完毕立即执行*/
onMounted(() => {
  search();
});
/*定义变量保存分页器的当前页数*/
const currentPage = ref(1);
/*定义变量保存分页器的每页显示多少条*/
const currentSize = ref(10);
/*定义变量保存数据总条目数*/
const total = ref();
/*修改每页显示多少条，触发此函数*/
const handleSizeChange = (val) => {
  console.log('每页展示' + val + '条数据');
  search();
}
/*修改当前页码，触发此函数*/
const handleCurrentChange = (val) => {
  console.log('当前的页数为：' + val);
  search();
}
/*
* 定义防抖搜索函数
* 当用户频繁触发搜索操作时，只有在最后一次触发后等待 300 毫秒内没有新的触发，才会执行 search 函数
* */
const debounceSearch = debounce(search, 300);

/*将数据导出为 Excel 文件*/
const exportToExcel = (data) => {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("Sheet1");

  // 添加表头
  const headers = Object.keys(data[0]);
  worksheet.addRow(headers);

  // 添加数据行
  data.forEach((item) => {
    const row = headers.map(header => item[header]);
    worksheet.addRow(row);
  });

  // 生成 Excel 文件并下载
  workbook.xlsx.writeBuffer().then((buffer) => {
    const blob = new Blob([buffer], { type: "application/octet-stream" });
    saveAs(blob, "药品信息.xlsx");
  });
};
/*定义编辑信息操作*/
const handleEdit = (index, row) => {
  console.log("点击了编辑按钮");
  console.log("当前行数据：{}",row);
  ElMessage({
    message: "编辑功能开发中...",
    type: "success"
  });
};
/*定义库存管理方法*/
const stockManage = (row) => {
  console.log("点击了库存管理按钮");
  console.log("当前行数据：{}",row);
  ElMessage({
    message: "库存管理功能开发中...",
    type: "success"
  });
};

</script>

<style scoped>


</style>